const puppeteer = require('puppeteer');
const axios = require('axios');
const xlsx = require('node-xlsx');
const fs = require('fs');

let isRandomMove = true;
let path = 'c://fuel/fuel_address.xlsx';

async function exportAddresses(psw) {

  let browser = await getBrowser();
  let newPage = await browser.newPage();
  await gotoAddresses(newPage, psw);
  await sleep(5000);
  //选地址
  const items = await newPage.$$(
    '.fuel_CardList>article',
  );
  const data = new Array();
  for (const item of items) {
    const name = await item.$(
      'h6',
    );
    const address = await item.$(
      'p',
    );

    const nameText = await newPage.evaluate(a => a.innerText, name);
    const addresstext = await newPage.evaluate(b => b.innerText, address);
    data.push([nameText, addresstext]);
  }
  console.log(data.toString());

  const list = [
    {
      name: '地址', // 工作薄的名称
      data: data,
    },
  ];
  const buffer = xlsx.build(list);
  let result = false;
  await fs.writeFile(path, buffer, function (err) {
    if (err) {
      console.log(err, '导出excel失败');
    } else {
      console.log('导出excel成功!');
      result = true;
    }

  });
  await sleep(3000);
  await newPage.close();
  return result;
}

async function getBrowser() {
  let wsKey = await axios.get('http://localhost:9222/json/version');
  let browser = await puppeteer.connect({
    browserWSEndpoint: wsKey.data.webSocketDebuggerUrl,
    defaultViewport: null,
  });

  return browser;
}

async function gotoAddresses(newPage, psw) {
  await newPage.goto('chrome-extension://dldjpboieedgcmpkchcjcbijingjcgok/popup.html#/wallet');

  await unlock(newPage);

  await sleep(2000);

  const accs = await newPage.$(
    'button[aria-label="Accounts"]',
  );

  await accs.click();

  await sleep(1000);

  return newPage;
}
async function unlock(newPage,psw) {
  try {
    await sleep(2000);
    const btn = await newPage.$(
      'button[intent="primary"]',
    );
    const gameName = await newPage.evaluate(btn => btn.textContent, btn);
    if (gameName.includes('Unlock')) {
      const pass = await newPage.$(
        'input[type="password"]',
      );
      await pass.click({ clickCount: 3 });
      await pass.type(psw);
    }
    // await btn.click();
  } catch (e) {
    console.log(e);
  }
}
async function disConnect(newPage,psw) {
  await newPage.goto('chrome-extension://dldjpboieedgcmpkchcjcbijingjcgok/popup.html#/wallet');
  await sleep(1000);
  await unlock(newPage,psw);

  //解除关联
  const button = await newPage.$(
    'button[aria-label="Menu"]',
  );
  await button.click();
  await sleep(1000);
  const Menu = await newPage.$(
    'li[data-key="connected-apps"]',
  );
  await Menu.click();
  await sleep(1000);

  const dels = await newPage.$$(
    'button[aria-label="Delete"]',
  );
  for (const item of dels) {
    await item.click();
    await sleep(1000);
    const con = await newPage.$(
      'button[aria-label="Confirm delete"]',
    );
    await con.click();
    await sleep(1000);
  }

  return newPage;
}
function sleep(ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  });
}

async function refreshAccount(psw, currentItem) {
  let browser = await getBrowser();

  let newPage = await browser.newPage();

  await disConnect(newPage,psw);

  await gotoAddresses(newPage, psw);
  //选地址

  const addresses = await newPage.$$(
    '.fuel_Box-flex>.fuel_Box-flex>.fuel_Box-flex>.address',
  );

  const sheets = xlsx.parse(path);
  const sheetElement = sheets[0].data[currentItem];
  const excuAddress = sheetElement[1].trim();

  for (const address of addresses) {
    const addresstext = await newPage.evaluate(ads => ads.textContent, address);

    if (addresstext.trim() === excuAddress.trim()) {
      console.log(addresstext + '---' + excuAddress);

      await address.click();
    }
  }

  await sleep(1000);
  await newPage.close();
  return excuAddress;
  //领水

  // const btns = await newPage.$$(
  //   'button[intent="primary"]',
  // );
  // for (const btn of btns) {
  //   const btntext = await newPage.evaluate(btn => btn.textContent, btn);
  //
  //   if (btntext.includes('Faucet')){
  //     await btn.click();
  //   }
  // }

  // await newPage.close();
}

module.exports.exportAddresses  = exportAddresses;
module.exports.refreshAccount  = refreshAccount;
